;(function(RCS){
    //从RCS中获取到相应的方法
    var utils = RCS.utils;
    var emoji = RCS.emoji;
    var render = utils.render;
    //构造回话函数
    var conversation = {};//{lastSendTime:0,messageContent:[]}
    //最后一次发送回话的时间
    conversation.lastSendTime = 0;
    //回话发送的信息内容
    conversation.messageContent = [];
    //重置语音播放为空
    var templates = {};
    //var $ = utils.$;    //返回一个集合$(".app")
    var terminal;   //终端
    var supportNot = false;//页面是否支持notification
    //加载模板  得到一些列html文件
    var getTemplates = function(callback){
        templates = RCS.getTemplates();
        callback && callback();
    }
    //创建button
    var createButton = function(config){
        //获取button模板，插入到当前的页面（消息列表面板）
        config.target.innerHTML = render(templates.button);
        //创建一个会话列表
        createIMConversation(config);
    }
    var createIMConversation = function(config){
        var data = {
            "showConversitionList": true
        }
        var callback = function(list){
            var obj = {};
            obj.list = list;
            data.conversationList = render(templates.conversation, obj);
            $(".customer-service")[0].innerHTML = render(templates.imMain,data);
        }
        //获取会话列表
        getConversationList(callback);
    }
    //获取会话列表////////////////////////////////////获取列表接口
    var getConversationList = function(callback){
        RongIMClient.getInstance().getConversationList({
            onSuccess: function(list) {
                 console.log(list);
                var _list = [];
                for (var i = 0; i < list.length; i++) {
                    if (list[i].conversationType == RongIMLib.ConversationType.PRIVATE) {
                        _list.push(list[i]);
                    }
                }
                var temp = _list[0];
                for (var i = 0; i < _list.length; i++) {
                    for (var j = i+1; j < _list.length; j++) {
                        if (_list[i].sentTime < _list[j].sentTime) {
                            var temp = _list[i];
                            _list[i] = _list[j];
                            _list[j] = temp;
                        }
                    }
                }
                callback && callback(_list);
            },
            onError: function(error) {
                // do something...
            }
        },null);
    }
    //开始会话（点击事件）
    var startConversation = function(event){
        var thisTarget = event.target || event.srcElement;
        //当点击X  删除当前会话（rongcloud-sprite）删除的class
        if (thisTarget.className.indexOf('rongcloud-sprite') != -1) {//存在rongcloud-sprite
            //从当前列表中移除
            event.currentTarget.parentNode.removeChild(event.currentTarget);
            //删除会话
            removeConversation(event.currentTarget.getAttribute("_cid"));
            return;
        }
        //阻止重复点击当前对话列表，重复点击跳出当前程序
        if (conversation.id == event.currentTarget.getAttribute("_cid")) {
            console.log("不要重复点击");
            return;
        }
        conversation.messageContent = [];
        conversation.id = event.currentTarget.getAttribute("_cid");
        conversation.mcount = event.currentTarget.getAttribute('_mcount');
        console.log(conversation);
        if (conversation.mcount != 0) {
            //记录当前未读的新消息个数（.rongcloud-badge）
            //当有新消息数的时候，点击当前列表清除新消息的的标签
            var badge = event.currentTarget.querySelector('.rongcloud-badge');
            //如果存在，则移除当前标签//并清除未读消息数
            if (badge) {
                badge.parentNode.removeChild(badge);
                //清除未读消息数
                clearUnreadCount(conversation.id);
            }
        }
        //跳转到会话页面打开会话
        window.location.href="conversation.html?cid="+conversation.id+"&mcount="+ conversation.mcount;
    }
   // 删除会话/////////////////////////////////删除会话接口
    var removeConversation = function(targetId){
        RongIMClient.getInstance().removeConversation(RongIMLib.ConversationType.PRIVATE,targetId,{
            onSuccess:function(bool){
                console.log('删除会话成功');
                // 删除会话成功。
            },
            onError:function(error){
                // error => 删除会话的错误码
            }
        });
    }
    //更新会话列表
    var updateConversationList = function(){
        var callback = function(list){
            console.log(list);
            var obj = {};
            obj.list = list;
            $('.rcs-conversation-list')[0].innerHTML = render(templates.conversation, obj);
        }
        //获取会话列表
        getConversationList(callback);
    }
    //清除未读消息数///////////////////////////清除未读消息接口
    var clearUnreadCount = function(targetId){
        var conversationType = RongIMLib.ConversationType.PRIVATE;
        RongIMClient.getInstance().clearUnreadCount(conversationType,targetId,{
            onSuccess:function(){
                console.log('清除未读消息成功');
                // 清除未读消息成功。
            },
            onError:function(error){
                // error => 清除未读消息数错误码。
            }
        });
    }
    //链接融云
    var sdkInit = function(params, callbacks){
        var appKey = params.appKey;
        var token = params.token;
        var navi = params.navi || "";

        if(navi !== ""){
            //私有云
            var config = {
                navi : navi
            };
            console.log("私有云");
            RongIMLib.RongIMClient.init(appKey,null,config);
        }else{
            //公有云
            console.log("公有云");
            RongIMLib.RongIMClient.init(appKey);
        }

        var instance = RongIMClient.getInstance();

        // 连接状态监听器
        RongIMClient.setConnectionStatusListener({
            onChanged: function (status) {
                console.log(status);
                var connectDom = $('.rcs-connect-status')[0];
                if (connectDom) {
                    connectDom.style.display = 'block';
                }
                switch (status) {
                    case RongIMLib.ConnectionStatus.CONNECTED:
                        if (connectDom) {
                            connectDom.style.display = 'none';
                        }
                        callbacks.getInstance && callbacks.getInstance(instance);
                        break;
                    case RongIMLib.ConnectionStatus.CONNECTING:
                        console.log('正在链接');
                        break;
                    case RongIMLib.ConnectionStatus.DISCONNECTED:
                        console.log('断开连接');
                        break;
                    case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                        console.log('其他设备登录');
                        break;
                    case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                        console.log('域名不正确');
                        break;
                    case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                        console.log('网络不可用');
                        break;
                    case RongIMLib.ConnectionStatus.DISCONNECTED:
                        console.log('断开连接');
                        break;
                    case 4:
                        console.log('token无效');
                        break;
                    default:
                        console.log('未知错误');
                        break;
                }
            }
        });

        RongIMClient.setOnReceiveMessageListener({
            // 接收到的消息
            onReceived: function (message) {
                // 判断消息类型
                console.log("新消息: " + message.targetId);
                if (message.offLineMessage) {
                    return;
                }
                if (message.conversationType == RongIMLib.ConversationType.PRIVATE) {
                    if (message.targetId == conversation.id) {
                        //显示新消息
                       // updateMessage(message);
                        //清除未读消息数
                       // clearUnreadCount(conversation.id);
                    }
                    updateConversationList();
                }
            }
        });

        //开始链接  ///////////////////////////////////////////链接开始接口
        RongIMClient.connect(token, {
            onSuccess: function(userId) {
                callbacks.getCurrentUser && callbacks.getCurrentUser(userId);
                console.log("链接成功，用户id：" + userId);

            },
            onTokenIncorrect: function() {
                console.log('token无效');
            },
            onError:function(errorCode){
                console.log("=============================================");
                console.log(errorCode);
            }
        });
    }
    //初始化init
    var init = function(config){
        RCS.config = config;
        config.isIM = true;
        var callbacks = {
            getInstance: function(instance){
                var callback = function(){
                    if (RCS.config.templates) {
                        for (var index in RCS.config.templates) {
                            templates[index] = RCS.config.templates[index];
                        }
                    }
                }
                //加载模板  得到一些列html文件
                getTemplates(callback);
                //创建button
                createButton(config);
            },
            getCurrentUser: function(userId){
            }
        }
        sdkInit(config,callbacks);
    }
    //对外暴露
    RCS.init = init;//im组件初始化
    RCS.startConversation = startConversation;//开始会话
})(RCS);